package com.android.net.util
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import androidx.core.app.NotificationCompat
import com.android.net.service.DownloadCommonBinder

class DownloadNotificationManager(private val context: Context) {
    private val notificationManager =
        context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    private val notificationId = 1
    private val channelId = "download_channel"

    init {
        createNotificationChannel()
    }

    // 创建通知渠道（Android 8.0 及以上需要）
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                "Download Progress",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "Shows download progress"
            }
            notificationManager.createNotificationChannel(channel)
        }
    }

    // 更新通知
    fun updateNotification(
        tasks: List<DownloadCommonBinder.DownloadTask>,
        totalTasks: Int
    ) {
        val notification = buildNotification(tasks, totalTasks)
        notificationManager.notify(notificationId, notification)
    }

    // 构建通知
    private fun buildNotification(
        tasks: List<DownloadCommonBinder.DownloadTask>,
        totalTasks: Int
    ): Notification {
        val notificationBuilder = NotificationCompat.Builder(context, channelId)
            .setSmallIcon(android.R.drawable.stat_sys_download)
            .setContentTitle("Downloading $totalTasks files")
            .setContentText("Download in progress")
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setOnlyAlertOnce(true)
            .setOngoing(true)

        // 添加每个任务的进度条
        tasks.forEach { task ->
            val fileName = task.file?.name ?: "Unknown"
            val progress = (task.totalBytesRead * 100 / task.contentLength).toInt()
            notificationBuilder.addAction(
                NotificationCompat.Action(
                    0,
                    "$fileName: $progress%",
                    null
                )
            )
        }

        return notificationBuilder.build()
    }

    // 取消通知
    fun cancelNotification() {
        notificationManager.cancel(notificationId)
    }
}